package com.westcom.vulb.activity;

import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.*;

import com.westcom.vulb.activity.CardGoodFragment.LoadProfileImg;
import com.westcom.vulb.activity.CardGoodFragment.User;
import com.westcom.vulb.logic.CardDetail;
import com.westcom.vulb.logic.SessionManager;
import com.westcom.vulb.logic.account;
import com.westcom.vulb.logic.card;
import com.westcom.vulb.logic.comment;
import com.westcom.vulb.protocal.http.Response;
import com.westcom.vulb.util.MyLog;
import com.westcom.vulb.util.Time;

public class CardCommentFragment extends CardInfoBasicFragment {
    
    
    private ListView mListView;
    private ViewAdapter mAdatper;
    
    private LoadCommentsTask mCommentLoader = null;
    private DeleteCommentTask mCommentDeleter = null;
    private NewCommentTask mCommentNewer = null;
    private ArrayList<Comment> mComments = null;
    
    private SessionManager sm = null;
    private boolean isEditMode = false;
    private LinearLayout ll_edit_layout = null;
    private Button btn_send_comment;
    private EditText et_edit_comment;
    private int mIndexToDele = -1;
    private OnClickListener l = new OnClickListener()
    {

		@Override
		public void onClick(View v) 
		{
			// TODO Auto-generated method stub
			switch(v.getId())
			{
				case R.id.iv_card_comment_item_right_delete_comment:
				{
					mIndexToDele = (Integer) v.getTag();
					showdeleConfrimdialog(mIndexToDele);
				}break;
				case R.id.btn_card_comment_send:
				{
					String comment = et_edit_comment.getText().toString();
					if(comment.isEmpty())
					{
						selfActivity().launchToast(R.string.comment_empty_error);
						return;
					}
					btn_send_comment.setFocusable(true);
					btn_send_comment.requestFocus();
					newComment(comment);
				}break;
				default:{}break;
			}
			
		}};

    @Override
    public void onAttach(Activity activity) 
    {
        super.onAttach(activity);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.card_comment, container, false);
        
        mListView = (ListView) v.findViewById(R.id.card_comment_list);
        mAdatper = new ViewAdapter(getActivity(), R.layout.card_comment_item, mComments);
        mListView.setAdapter(mAdatper);
        
        btn_send_comment = (Button)v.findViewById(R.id.btn_card_comment_send);
        et_edit_comment = (EditText)v.findViewById(R.id.et_card_comment_edit_comment);
        ll_edit_layout = (LinearLayout)v.findViewById(R.id.ll_card_comment_send_comment);
        btn_send_comment.setOnClickListener(l);
        return v;
    }
    
    @Override
    public void onResume() 
    {
        super.onResume();
        sm = SessionManager.getInstance();
        MyLog.d("onResume start");
        if (mComments == null) 
        {
            MyLog.d("onResume loadComment:");
            loadComments();
        } else 
        {
            mAdatper.setData(mComments);
            MyLog.d("onResume commentLen:" + mComments.size());
        }
    }

    @Override
    public void onPause() {
        super.onPause();
    }
    
    @Override
    public void onPrepareOptionsMenu(Menu menu) {
        super.onPrepareOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onCardDetailLoaded() 
    {
    }
    
    private void loadComments() 
    {
        MyLog.d("loadComments start");
        if(null == mCommentLoader)
        {
        	mLoadingDialog.show();
	    	if(null == mComments)
	    	{
	    		mComments = new ArrayList<Comment>();
	    	}else
	    	{
	    		mComments.clear();
	    	}
	        MyLog.d("loadComments real start");
        	mCommentLoader = new LoadCommentsTask();
        	mCommentLoader.execute(new Integer[] {selfActivity().mCardId});
        }
    }
    private void deleteComment(int index)
    {
    	if(mCommentDeleter == null)
    	{
    		mLoadingDialog.show();
    		Comment c = mComments.get(index);
    		mCommentDeleter = new DeleteCommentTask();
    		mCommentDeleter.execute(new Integer [] {c.commentId});
    	}
    	return;
    }
    
    private void newComment(String content)
    {
    	if(mCommentNewer == null)
    	{
    		mLoadingDialog.show();
    		mCommentNewer = new NewCommentTask();
    		mCommentNewer.execute(new String [] {content});
    	}
    	return;
    }
    
    @Override
    public void onLogoLoaded(Integer uid, Bitmap logo) 
    {
    }
    public class ViewAdapter extends BaseAdapter 
    {
        private Context mContext;
        private int mLayoutId;
        private ArrayList<Comment> mData;
        private LayoutInflater mInflater;
        
        private Bitmap mDefaultLogo;

        public ViewAdapter(Activity activity, int layoutId, ArrayList<Comment> comments) {
            mContext = activity;
            mLayoutId = layoutId;
            mData = comments;
            
            mInflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }

        @Override
        public int getCount() 
        {
            if (mData == null || mData.size() <= 0) 
            {
                return 0;
            }
            return mData.size();
        }

        @Override
        public Object getItem(int position) 
        {
            if (mData == null || mData.size() <= 0) {
                return null;
            }
            return mData.get(position);
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View v = convertView;
            if (v == null) {
                v = mInflater.inflate(mLayoutId, parent, false);
            }
            if (mDefaultLogo == null) 
            {
                mDefaultLogo = BitmapFactory.decodeResource(getResources(), R.drawable.sharemember_tab_normal);
            }
            int index = mData.size()-1-position;
            Comment comment = mData.get(index);
            
            int currUid = SessionManager.getInstance().getCurrUid();
            int uid = comment.userId;
            
            View detail = null;
            View left = v.findViewById(R.id.card_comment_item_left);
            View right = v.findViewById(R.id.card_comment_item_right);
            if (currUid == uid) 
            {
                detail = right;
                left.setVisibility(View.GONE);
            } else 
            {
                detail = left;
                right.setVisibility(View.GONE);
            }
            ((TextView)detail.findViewById(R.id.name)).setText(comment.userName);
            String formatTime = Time.formatTime(comment.updateDate);
            ((TextView)detail.findViewById(R.id.time)).setText(formatTime);
            ((TextView)detail.findViewById(R.id.comment)).setText(comment.content);
            //image view
            ImageView iv_profile_img = (ImageView) detail.findViewById(R.id.user_logo);
            comment.v = iv_profile_img;
            Bitmap bmp = comment.img;
            if (bmp != null && comment.v != null) 
            {
            	comment.v.setImageBitmap(bmp);
            }else
            {
            	LoadProfileImgTask loadImg = new LoadProfileImgTask();
            	loadImg.equals(new Integer[]{comment.userId});
            }
            
            ImageView iv_delete_comment = (ImageView)v.findViewById(R.id.iv_card_comment_item_right_delete_comment);
            iv_delete_comment.setTag(index);
            iv_delete_comment.setOnClickListener(l);
            if(currUid == uid)
            {
            	if(isEditMode)
                {
                	iv_profile_img.setVisibility(View.GONE);
                	iv_delete_comment.setVisibility(View.VISIBLE);
                }else
                {
                	iv_profile_img.setVisibility(View.VISIBLE);
                	iv_delete_comment.setVisibility(View.GONE);
                }
            }
            return v;
        }
        
        public void setData(ArrayList<Comment> data) 
        {
            mData = data;
            notifyDataSetChanged();
        }
    }
    
    public class LoadCommentsTask extends AsyncTask<Integer, Integer, String> 
    {
        @Override
        protected String doInBackground(Integer... params) 
        {
            JSONArray ja = new JSONArray();
            int cardId = params[0];
            for(int i:params)
            {
            	JSONObject j = new JSONObject();
            	try 
            	{
					j.put("cardId",i);
				} catch (JSONException e) 
				{
					// TODO Auto-generated catch block
					e.printStackTrace();
					return selfActivity().getResources().getString(R.string.params_error);
				}
            	ja.put(j);
            }
            comment c = comment.getInstanse();
            Response res = c.GetCommentList(sm.getCurrSessionId(), ja);
            if(Response.SUCCESS != res.errno)
            {
            	return res.errmsg;
            }
            HashMap<String, Object> commentData = (HashMap<String, Object>)res.data.get("cards");
            JSONArray commentList = (JSONArray)commentData.get(""+cardId);
            for(int i = 0;i<commentList.length();i++)
            {
            	JSONObject co;
				try 
				{
					co = commentList.getJSONObject(i);
				} catch (JSONException e) 
				{
					// TODO Auto-generated catch block
					e.printStackTrace();
					continue;
				}
            	Comment tmp = new Comment(co);
            	res = sm.getCurrentSession().getProfileImage(true, tmp.userId);
                if(res.errno == Response.SUCCESS)
                {
                	String bitmap_str = (String) res.data.get("personImg");
                	tmp.img = account.Base64Str2Bitmap(bitmap_str);
                }
            	mComments.add(tmp);
            }
            return null;
        }
        @Override
        protected void onCancelled() 
        {
            super.onCancelled();
            if(mLoadingDialog.isShowing())
        	{
        		mLoadingDialog.hide();
        	}
        }
        @Override
        protected void onPostExecute(String result) 
        {
            super.onPostExecute(result);
            if(mLoadingDialog.isShowing())
        	{
        		mLoadingDialog.hide();
        	}
            mCommentLoader = null;
            if(result != null)
            {
            	selfActivity().launchToast(result);
            	return;
            }
            mAdatper.setData(mComments);
            
        }
    }
    
    private class DeleteCommentTask extends AsyncTask<Integer, Integer, String> {
        @Override
        protected String doInBackground(Integer... params) 
        {
        	int commentId = params[0];
        	comment c = comment.getInstanse();
        	Response res = c.DeleteComment(sm.getCurrSessionId(), commentId);
        	if(res.errno != Response.SUCCESS)
        	{
        		 return res.errmsg;
        	}else
        	{
        		return null;
        	}
        }
        @Override
        protected void onCancelled() {
            super.onCancelled();
            if(mLoadingDialog.isShowing())
        	{
        		mLoadingDialog.hide();
        	}
        }
        @Override  
        protected void onPostExecute(String result) 
        {  
        	super.onPostExecute(result);
        	if(mLoadingDialog.isShowing())
        	{
        		mLoadingDialog.hide();
        	}
        	mCommentDeleter = null;
        	if(result != null)
        	{
        		selfActivity().launchToast(result);
        	}
        	loadComments();
        }
	}
    
    private class NewCommentTask extends AsyncTask<String, Integer, String> {
        @Override
        protected String doInBackground(String... params) 
        {
        	String content = params[0];
        	comment c = comment.getInstanse();
        	Response res = c.CreateComment(sm.getCurrSessionId(), selfActivity().mCardId, 0, content);
        	if(res.errno != Response.SUCCESS)
        	{
        		 return res.errmsg;
        	}else
        	{
        		return null;
        	}
        }
        @Override
        protected void onCancelled() {
            super.onCancelled();
            if(mLoadingDialog.isShowing())
        	{
        		mLoadingDialog.hide();
        	}
        }
        @Override  
        protected void onPostExecute(String result) 
        {  
        	super.onPostExecute(result);
        	if(mLoadingDialog.isShowing())
        	{
        		mLoadingDialog.hide();
        	}
        	mCommentNewer = null;
        	if(result != null)
        	{
        		selfActivity().launchToast(result);
        	}
        	et_edit_comment.setText("");
        	btn_send_comment.requestFocus();
        	loadComments();
        }
	}
    
    public class Comment
    {
    	int cardId;
    	int commentId;
    	String content;
    	int good;
    	int toUserId;
    	String toUserName;
    	String updateDate;
    	int userId;
    	String userName;
    	int verNo;

    	Bitmap img;
    	ImageView v;
    	public Comment(JSONObject data)
    	{
    		try 
    		{
				cardId = data.getInt("cardId");
				commentId = data.getInt("commentId");
	    		content = data.getString("content");
	    		good = data.getInt("good");
	    		toUserId = data.getInt("toUserId");
	    		toUserName = data.getString("toUserName");
	    		updateDate = data.getString("updateDate");
	    		userId = data.getInt("userId");
	    		userName = data.getString("userName");
	    		verNo = data.getInt("verNo");
			} catch (JSONException e) 
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
    	}
    }
    
    class LoadProfileImgTask extends AsyncTask<Integer, Integer, String> 
    {
    	private int userId;
        @Override
        protected String doInBackground(Integer... params) 
        {
        	userId = params[0];
        	int index = getUserById(userId);
        	if(index <0)
        	{
        		return selfActivity().getResources().getString(R.string.load_profile_img_error);
        	}
        	Comment c = mComments.get(index);
            Response res = sm.getCurrentSession().getProfileImage(true,userId);
            if(res.errno != Response.SUCCESS)
            {
            	return res.errmsg;
            }
            String bitmap_str = (String) res.data.get("personImg");
        	c.img = account.Base64Str2Bitmap(bitmap_str);
        	if(c.v != null && null != c.img)
        	{
        		c.v.setImageBitmap(c.img);
        	}
            return null;
        }
        @Override
        protected void onPostExecute(String result) 
        {
            super.onPostExecute(result);
            MyLog.d("commentList: onPostExecute");
            if(result != null)
            {
            	selfActivity().launchToast(result);
            	return;
            }
            int index = getUserById(userId);
        	Comment c = mComments.get(index);
        	if(c.v != null && null != c.img)
        	{
        		c.v.setImageBitmap(c.img);
        	}
        }
    }
    public int getUserById(int userId)
    {
    	int index = -1;
    	Comment c = null;
    	for(int i = 0;i<mComments.size();i++)
    	{
    		c = mComments.get(i);
    		if(c.userId == userId)
    		{
    			index = i;
    		}
    	}
    	return index;
    }
    public void SwitchMod()
    {
    	isEditMode = !isEditMode;
		if(isEditMode)
		{
			ll_edit_layout.setVisibility(View.GONE);
		}else
		{
			ll_edit_layout.setVisibility(View.VISIBLE);
		}
		mAdatper.notifyDataSetChanged();
    }
    protected void showdeleConfrimdialog(int index) 
	{
		AlertDialog.Builder builder = new Builder(selfActivity());
		builder.setTitle(mComments.get(index).content);
		builder.setMessage(R.string.del_confirm);
		builder.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener()
		{
			@Override
			public void onClick(DialogInterface dialog, int which) 
			{
				// TODO Auto-generated method stub
				deleteComment(mIndexToDele);
				dialog.dismiss();
			}});
		
		builder.setNegativeButton(R.string.no, new DialogInterface.OnClickListener()
		{
			@Override
			public void onClick(DialogInterface dialog, int which) 
			{
				// TODO Auto-generated method stub
				dialog.dismiss();
			}});
		builder.create().show();
	}
}